import {useState, useCallback} from 'react'
import Taro from '@tarojs/taro'

// 图片预览相关类型
interface PreviewImageOptions {
  current?: string
  urls: string[]
  showmenu?: boolean
}

// 选择图片相关类型
interface ChooseImageOptions {
  count?: number
  sizeType?: ('original' | 'compressed')[]
  sourceType?: ('album' | 'camera')[]
}

// 保存图片相关类型
interface SaveImageOptions {
  filePath: string
}


// 振动相关类型
interface VibrateOptions {
  type?: 'light' | 'medium' | 'heavy'
}

// 剪贴板相关类型
interface ClipboardOptions {
  data: string
}

// 返回的 hooks 类型
interface UseTaroApisReturn {
  // 图片相关
  previewImage: (options: PreviewImageOptions) => Promise<void>
  chooseImage: (options?: ChooseImageOptions) => Promise<string[]>
  saveImage: (options: SaveImageOptions) => Promise<void>


  // 振动
  vibrateShort: (options?: VibrateOptions) => Promise<void>
  vibrateLong: () => Promise<void>

  // 剪贴板
  setClipboardData: (options: ClipboardOptions) => Promise<void>
  getClipboardData: () => Promise<string>

  // 系统信息
  getSystemInfo: () => Promise<Taro.getSystemInfoSync.Result>

  // 网络状态
  getNetworkType: () => Promise<{ networkType: string }>

  // 设备信息
  getDeviceInfo: () => Promise<{
    brand: string
    model: string
    system: string
    platform: string
  }>

  // 加载状态
  loading: {
    show: (title?: string) => Promise<void>
    hide: () => Promise<void>
  }

  // Toast 提示
  toast: {
    show: (title: string, icon?: 'success' | 'loading' | 'none', duration?: number) => Promise<void>
    success: (title: string, duration?: number) => Promise<void>
    error: (title: string, duration?: number) => Promise<void>
  }

  // 模态框
  modal: {
    show: (title: string, content: string, showCancel?: boolean) => Promise<{ confirm: boolean; cancel: boolean }>
    confirm: (title: string, content: string) => Promise<boolean>
    alert: (title: string, content: string) => Promise<void>
  }

  // 操作菜单
  actionSheet: {
    show: (itemList: string[], itemColor?: string) => Promise<number>
  }

  // 状态
  isRecording: boolean
  isPlaying: boolean
}

/**
 * Taro API 封装 Hook
 * 提供常用的 Taro 内置 API 的便捷调用方法
 */
export const useTaroApis = (): UseTaroApisReturn => {
  const [isRecording] = useState(false)
  const [isPlaying] = useState(false)

  // 图片预览
  const previewImage = useCallback(async (options: PreviewImageOptions) => {
    try {
      await Taro.previewImage(options)
    } catch (error) {
      console.error('图片预览失败:', error)
      throw error
    }
  }, [])

  // 选择图片
  const chooseImage = useCallback(async (options: ChooseImageOptions = {}) => {
    try {
      const result = await Taro.chooseImage({
        count: 9,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        ...options
      })
      return result.tempFilePaths
    } catch (error) {
      console.error('选择图片失败:', error)
      throw error
    }
  }, [])

  // 保存图片
  const saveImage = useCallback(async (options: SaveImageOptions) => {
    try {
      await Taro.saveImageToPhotosAlbum({
        filePath: options.filePath
      })
      Taro.showToast({
        title: '保存成功',
        icon: 'success'
      })
    } catch (error) {
      console.error('保存图片失败:', error)
      throw error
    }
  }, [])

  // 短振动
  const vibrateShort = useCallback(async (options: VibrateOptions = {}) => {
    try {
      await Taro.vibrateShort({
        type: options.type || 'light'
      })
    } catch (error) {
      console.error('短振动失败:', error)
      throw error
    }
  }, [])

  // 长振动
  const vibrateLong = useCallback(async () => {
    try {
      await Taro.vibrateLong()
    } catch (error) {
      console.error('长振动失败:', error)
      throw error
    }
  }, [])

  // 设置剪贴板
  const setClipboardData = useCallback(async (options: ClipboardOptions) => {
    try {
      await Taro.setClipboardData({
        data: options.data
      })
      Taro.showToast({
        title: '已复制到剪贴板',
        icon: 'success'
      })
    } catch (error) {
      console.error('设置剪贴板失败:', error)
      throw error
    }
  }, [])

  // 获取剪贴板
  const getClipboardData = useCallback(async () => {
    try {
      const result = await Taro.getClipboardData()
      return result.data
    } catch (error) {
      console.error('获取剪贴板失败:', error)
      throw error
    }
  }, [])

  // 获取系统信息
  const getSystemInfo = useCallback(async () => {
    try {
      return Taro.getSystemInfoSync()
    } catch (error) {
      console.error('获取系统信息失败:', error)
      throw error
    }
  }, [])

  // 获取网络状态
  const getNetworkType = useCallback(async () => {
    try {
      const result = await Taro.getNetworkType()
      return {networkType: result.networkType}
    } catch (error) {
      console.error('获取网络状态失败:', error)
      throw error
    }
  }, [])

  // 获取设备信息
  const getDeviceInfo = useCallback(async () => {
    try {
      const systemInfo = Taro.getSystemInfoSync()
      return {
        brand: systemInfo.brand,
        model: systemInfo.model,
        system: systemInfo.system,
        platform: systemInfo.platform
      }
    } catch (error) {
      console.error('获取设备信息失败:', error)
      throw error
    }
  }, [])

  // Loading 相关
  const loading = {
    show: useCallback(async (title: string = '加载中...') => {
      try {
        await Taro.showLoading({
          title,
          mask: true
        })
      } catch (error) {
        console.error('显示 Loading 失败:', error)
        throw error
      }
    }, []),
    hide: useCallback(async () => {
      try {
        await Taro.hideLoading()
      } catch (error) {
        console.error('隐藏 Loading 失败:', error)
        throw error
      }
    }, [])
  }

  // Toast 相关
  const toast = {
    show: useCallback(async (title: string, icon: 'success' | 'loading' | 'none' = 'none', duration: number = 2000) => {
      try {
        await Taro.showToast({
          title,
          icon,
          duration
        })
      } catch (error) {
        console.error('显示 Toast 失败:', error)
        throw error
      }
    }, []),
    success: useCallback(async (title: string, duration: number = 2000) => {
      try {
        await Taro.showToast({
          title,
          icon: 'success',
          duration
        })
      } catch (error) {
        console.error('显示成功 Toast 失败:', error)
        throw error
      }
    }, []),
    error: useCallback(async (title: string, duration: number = 2000) => {
      try {
        await Taro.showToast({
          title,
          icon: 'none',
          duration
        })
      } catch (error) {
        console.error('显示错误 Toast 失败:', error)
        throw error
      }
    }, [])
  }

  // 模态框相关
  const modal = {
    show: useCallback(async (title: string, content: string, showCancel: boolean = true) => {
      try {
        const result = await Taro.showModal({
          title,
          content,
          showCancel
        })
        return {
          confirm: result.confirm,
          cancel: result.cancel
        }
      } catch (error) {
        console.error('显示模态框失败:', error)
        throw error
      }
    }, []),
    confirm: useCallback(async (title: string, content: string) => {
      try {
        const result = await Taro.showModal({
          title,
          content,
          showCancel: true
        })
        return result.confirm
      } catch (error) {
        console.error('显示确认框失败:', error)
        throw error
      }
    }, []),
    alert: useCallback(async (title: string, content: string) => {
      try {
        await Taro.showModal({
          title,
          content,
          showCancel: false
        })
      } catch (error) {
        console.error('显示提示框失败:', error)
        throw error
      }
    }, [])
  }

  // 操作菜单相关
  const actionSheet = {
    show: useCallback(async (itemList: string[], itemColor: string = '#000000') => {
      try {
        const result = await Taro.showActionSheet({
          itemList,
          itemColor
        })
        return result.tapIndex
      } catch (error) {
        console.error('显示操作菜单失败:', error)
        throw error
      }
    }, [])
  }

  return {
    previewImage,
    chooseImage,
    saveImage,
    vibrateShort,
    vibrateLong,
    setClipboardData,
    getClipboardData,
    getSystemInfo,
    getNetworkType,
    getDeviceInfo,
    loading,
    toast,
    modal,
    actionSheet,
    isRecording,
    isPlaying
  }
}
